<template>
  <t-dialog
    :visible="visible"
    :title="editData ? '编辑商品' : '新增商品'"
    :width="800"
    @close="handleClose"
  >
    <t-form
      ref="formRef"
      :data="formData"
      :rules="formRules"
      layout="vertical"
    >
      <t-form-item label="商品标题" name="title">
        <t-input v-model="formData.title" placeholder="请输入商品标题" />
      </t-form-item>

      <t-form-item label="商品图片" name="image">
        <t-input v-model="formData.image" placeholder="请输入商品图片URL" />
      </t-form-item>

      <t-row :gutter="16">
        <t-col :span="12">
          <t-form-item label="售价" name="price">
            <t-input
              v-model="formData.price"
              type="number"
              placeholder="请输入商品售价"
            />
          </t-form-item>
        </t-col>
        <t-col :span="12">
          <t-form-item label="原价" name="originalPrice">
            <t-input
              v-model="formData.originalPrice"
              type="number"
              placeholder="请输入商品原价"
            />
          </t-form-item>
        </t-col>
      </t-row>

      <t-form-item label="商品链接" name="link">
        <t-input v-model="formData.link" placeholder="请输入商品链接" />
      </t-form-item>

      <t-form-item label="排序号" name="sortOrder">
        <t-input
          v-model="formData.sortOrder"
          type="number"
          placeholder="请输入排序号，越小越靠前"
        />
      </t-form-item>

      <t-form-item label="状态" name="status">
        <t-radio-group v-model="formData.status">
          <t-radio :value="1">正常</t-radio>
          <t-radio :value="0">禁用</t-radio>
        </t-radio-group>
      </t-form-item>

      <t-form-item label="标签文本" name="tagsText">
        <t-input
          v-model="formData.tagsText"
          placeholder="请输入标签，用空格分隔"
        />
      </t-form-item>

      <t-divider content="商品详情" />

      <t-form-item label="商品图片 gallery">
        <t-input
          v-model="detailForm.gallery"
          placeholder='JSON格式: ["url1","url2"]'
        />
      </t-form-item>

      <t-form-item label="商品规格 specs">
        <t-input
          v-model="detailForm.specs"
          placeholder='JSON格式: {"颜色":"红","尺寸":"M"}'
        />
      </t-form-item>

      <t-form-item label="详情HTML">
        <t-textarea
          v-model="detailForm.detailHtml"
          placeholder="请输入商品详情HTML"
          :rows="4"
        />
      </t-form-item>

      <t-form-item label="额外信息">
        <t-textarea
          v-model="detailForm.extraJson"
          placeholder="请输入额外信息JSON"
          :rows="3"
        />
      </t-form-item>
    </t-form>

    <template #footer>
      <t-button @click="handleClose">取消</t-button>
      <t-button type="primary" @click="handleSubmit">提交</t-button>
    </template>
  </t-dialog>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'
import commodityApi from '../../api/commodity';

// 接收父组件参数
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  editData: {
    type: Object,
    default: null
  }
});

//  emits
const emit = defineEmits(['close', 'success']);

// 表单引用
const formRef = ref(null);

// 商品主表表单数据
const formData = ref({
  id: null,
  title: '',
  image: '',
  price: null,
  originalPrice: null,
  link: '',
  sortOrder: 0,
  status: 1,
  tagsText: ''
});

// 商品详情表单数据
const detailForm = ref({
  id: null,
  commodityId: null,
  gallery: '[]',
  specs: '{}',
  detailHtml: '',
  extraJson: '{}',
  status: 1
});

// 表单验证规则
const formRules = ref({
  title: [{ required: true, message: '请输入商品标题', trigger: 'blur' }],
  price: [{ required: true, message: '请输入商品售价', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
});

// 重置表单
const resetForm = () => {
  formData.value = {
    id: null,
    title: '',
    image: '',
    price: null,
    originalPrice: null,
    link: '',
    sortOrder: 0,
    status: 1,
    tagsText: ''
  };

  detailForm.value = {
    id: null,
    commodityId: null,
    gallery: '[]',
    specs: '{}',
    detailHtml: '',
    extraJson: '{}',
    status: 1
  };
};

// 获取详情数据
const fetchDetail = async (commodityId) => {
  try {
    console.log(commodityId)
    const res = await commodityApi.getCommodityDetail(commodityId);
    if (res.data) {
      detailForm.value = { ...res.data };
    }
  } catch (err) {
    MessagePlugin.error('获取商品详情失败');
    console.error(err);
  }
};

// 监听编辑数据变化
watch(() => props.editData, (newVal) => {
  if (newVal) {
    // 填充主表数据
    formData.value = { ...newVal };
    console.log(formData.value)
    // 获取详情数据
    fetchDetail(newVal.id);
  } else {
    // 重置表单
    resetForm();
  }
}, { immediate: true });


// 关闭弹窗
const handleClose = () => {
  emit('close');
};

// 提交表单
const handleSubmit = async () => {
  // 表单验证
  const valid = await formRef.value.validate();
  if (!valid) return;

  try {
    if (formData.value.id) {
      // 更新商品
      // await commodityApi.updateCommodity(formData.value);
      // // 更新详情
      // if (detailForm.value.id) {
      //   await commodityApi.updateCommodityDetail(detailForm.value);
      // } else {
      //   detailForm.value.commodityId = formData.value.id;
      //   await commodityApi.saveCommodity(formData.value, detailForm.value);
      // }
      detailForm.value.commodityId = formData.value.id;
      await commodityApi.updateCommodity(formData.value, detailForm.value);
      MessagePlugin.success('更新成功');
    } else {
      // 新增商品
      await commodityApi.saveCommodity(formData.value, detailForm.value);
      MessagePlugin.success('新增成功');
    }
    emit('success');
  } catch (err) {
    MessagePlugin.error(formData.value.id ? '更新失败' : '新增失败');
    console.error(err);
  }
};
</script>
